package com.hctg.forced2sleep.activity;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.hctg.forced2sleep.R;
import com.hctg.forced2sleep.databinding.ActivityEnterPwdBinding;
import com.hctg.forced2sleep.bean.Global;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 程序锁输入密码页面
 * 1. 解决任务栈页面跳转bug,在清单文件中手动注册页面,启动模式设置成单例设计模式
 *
 * <activity
 * android:name=".activity.EnterPwdActivity"
 * android:launchMode="singleInstance"
 * android:excludeFromRecents="true" />
 *
 * 2. excludeFromRecents: 不让输入密码页面进入系统最近任务列表中
 *    如果这个Activity是整个Task的根Activity，整个Task将不会出现在最近任务列表中。
 */
public class EnterPwdActivity extends BaseActivity<ActivityEnterPwdBinding> {

    private        String         packageName;
    private        int            passwordLength;//密码长度
    private        Timer          timer = new Timer();//删除
    private        CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        passwordLength = getResources().getInteger(R.integer.passwordLength);
//        viewBinding.btn0.setOnClickListener(this::onClick);
//        viewBinding.btn1.setOnClickListener(this::onClick);
//        viewBinding.btn2.setOnClickListener(this::onClick);
//        viewBinding.btn3.setOnClickListener(this::onClick);
//        viewBinding.btn4.setOnClickListener(this::onClick);
//        viewBinding.btn5.setOnClickListener(this::onClick);
//        viewBinding.btn6.setOnClickListener(this::onClick);
//        viewBinding.btn7.setOnClickListener(this::onClick);
//        viewBinding.btn8.setOnClickListener(this::onClick);
//        viewBinding.btn9.setOnClickListener(this::onClick);
//        viewBinding.btnOk.setOnClickListener(this::onClick);
//        viewBinding.btnDelete.setOnClickListener(this::onClick);
//        viewBinding.btnDelete.setOnLongClickListener(this::onLongClick);

        init();
        initIntent();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        initIntent();
    }

    private void initIntent() {
        //获取AppLockService.java发过来的包名
        packageName = getIntent().getStringExtra(Global.PACKAGE_NAME);

        viewBinding.tvPackageName.setText(packageName);
        PackageManager pm = getPackageManager();
        try {
            ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
            String name = applicationInfo.loadLabel(pm).toString();
            Drawable icon = applicationInfo.loadIcon(pm);
            viewBinding.tvName.setText(name);
            viewBinding.ivIcon.setImageDrawable(icon);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    //初始化 & 输错后重写初始化 & 输入为空
    private void init() {
        viewBinding.tvMd5.setText(getMd5String());
        countDownTimer = new CountDownTimer(getCountDownSecond() * 1000, 500) {

            @Override
            public void onTick(long millisUntilFinished) {
                viewBinding.tvCountDown.setText(getStringFormat("%02d秒后重置密码", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                viewBinding.tvCountDown.setText("0秒后重置密码");
                init();
            }
        }.start();
    }

    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.btn_ok://确定
//                String text = getText(viewBinding.tvPwd);
//                if (!TextUtils.isEmpty(text)) {
//                    if (text.equals(getStringNum(getMd5String(), passwordLength))) {
//                        Global.aCache.put(packageName, packageName, 60);
//                        ToasterUtils.warning("这个App有效时间为1分钟");
//                        onBackPressed();
//                    } else {
//                        init();
//                        ToasterUtils.error("密码错误:" + viewBinding.tvPwd.getHint());
//                    }
//                } else {
//                    init();
//                    ToasterUtils.error("密码为空:" + viewBinding.tvPwd.getHint());
//                }
//                break;
//            case R.id.btn_delete://删除
//                deleteText();
//                break;
            default://0-9
                viewBinding.tvPwd.append(((Button) v).getText());
                break;
        }
    }
    public boolean onLongClick(View view) {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    if (view.isPressed()) {
                        deleteText();
                    } else {
                        cancel();//如果不是长按,就取消任务
                    }
                });
            }
        }, 0, 50);
        return true;
    }

    //删除文字
    private void deleteText() {
        String s = viewBinding.tvPwd.getText().toString();
        if (s.length() > 0) {
            viewBinding.tvPwd.setText(s.substring(0, s.length() - 1));
        }
    }

    /**
     * 获取倒计时秒数
     * @return 0-59
     */
    private int getCountDownSecond() {
        return 60 - Calendar.getInstance().get(Calendar.SECOND);
    }

    //获取现在时间md5
    private String getMd5String() {
        Calendar calendar = Calendar.getInstance();
        String time = TimeUtils.date2String(calendar.getTime(), "yyyyMMddHHmm");
        return EncryptUtils.encryptMD5ToString(time);
    }

    //提取字符串中数字
    private String getStringNum(String string, int maxLentgh) {
        char[] chars = string.toCharArray();
        String needReturn = "";
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                needReturn += chars[i];
            }
        }
        if (needReturn.length() > maxLentgh) {
            needReturn = needReturn.substring(0, maxLentgh);
        }
        return needReturn;
    }

    private void JumpToDesk() {
        ActivityUtils.startHomeActivity();
        //跳到桌面
//        Intent intent = new Intent(Intent.ACTION_MAIN, null);
//        intent.addCategory(Intent.CATEGORY_HOME);
//        startActivity(intent);
    }

    //拦截手机物理返回键
    @Override
    public void onBackPressed() {
        JumpToDesk();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();//取消后再调用timer.schedule()会报错
        countDownTimer.cancel();
    }
}
